# coding:utf-8

import os
import time
import json
import requests
import sys
reload(sys)
sys.setdefaultencoding('utf8')


def testyun_analyze(file_byte):
    url = 'http://www.ztdface.com/analyze'
    # url = 'http://127.0.0.1:5000/analyze'
    try:
        reponse = requests.post(url, files={'image': ('filename.jpg', file_byte)})
        return reponse
    except Exception as e:
        print e


def imagebyte(path):
    file = open(path, 'rb')
    file_byte = file.read()
    file.close()
    return file_byte


def main(path):
    dirlist = os.listdir(path)
    list_ok = []
    list_fail = {}
    count = 0
    # 遍历文件夹
    for name in dirlist:
        # 如果是图片，则去做请求
        if name.endswith('.jpg') or name.endswith('.png'):
            count += 1
            # time.sleep(0.1)
            print name,
            # 最多做3次请求，3次失败后，则跳过该图片。
            data = {}
            for i in range(3):
                try:
                    res = testyun_analyze(imagebyte(path + '/' + name))
                    data = json.loads(res.content)
                    print 'complete request',
                    # 进行结果的判断
                    if data.get('code', None) == 0:
                        list_ok.append(name)
                        print '-- ok'
                    else:
                        list_fail[name] = data['desc']
                        print '-- fail'
                except Exception as e:
                    print e
                    if i >= 2:
                        print ' : request fail'
                        list_fail[name] = 'request failed'
                    else:
                        time.sleep(0.5)
                else:
                    time.sleep(0.2)
                    break

    # 写入文件
    result = json.dumps(list_fail, ensure_ascii=False, indent=4)
    f = open('result.json', 'wb')
    f.write(result)
    f.close()


if __name__ == '__main__':
    main('image')
    print 'end-----'
